package com.hao.listener;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hao.enums.ComponentEnum;
import com.hao.ui.MainActivity;
import com.hao.utils.HttpUtils;
import com.hao.utils.StrKit;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Steven on 2017/7/22.
 */
public class MyActionListener implements ActionListener {

    private ComponentEnum componentEnum;

    private MainActivity mainActivity;

    private boolean isReStart = false;

    private Long la;

    public MyActionListener(ComponentEnum componentEnum, MainActivity mainActivity) {
        this.componentEnum = componentEnum;
        this.mainActivity = mainActivity;
    }

    public void actionPerformed(ActionEvent e) {
        switch (componentEnum) {
            case BUTTON_SEND: initFirst(); break;
            case BUTTON_ADD_HEADER: addRow(ComponentEnum.BUTTON_ADD_HEADER);break;
            case BUTTON_ADD_REQUEST: addRow(ComponentEnum.BUTTON_ADD_REQUEST);break;
            case BUTTON_TEST: send();break;
            case BUTTON_RESTART: restart();break;
        }
    }

    private void restart() {
        if(la == null) {
            mainActivity.getTextArea_res().setText("当前无执行计划，不可重启\r\n");
            return ;
        }
        isReStart = true;
        mainActivity.getTextArea_res().append("已设置重新启动\r\n");
    }

    private void initFirst() {
        Date now = new Date();
        SimpleDateFormat df_normal = new SimpleDateFormat("HH");
        Integer hours = Integer.parseInt(df_normal.format(now));
        df_normal = new SimpleDateFormat("yyyy-MM-dd");
        String date = df_normal.format(now);
        String dates = String.format(date + " %02d:00:00:000", hours + 1);
        df_normal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        Date after = now;
        try {
            after = df_normal.parse(dates);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        la = after.getTime() - now.getTime();
        new Thread(() -> {
            try {
                Thread.sleep(la);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            initRepeatService();
        }).start();
        mainActivity.getTextArea_res().setText("初始化第一次发送时间，第一次发送将在" + la / 1000 + "秒后执行\r\n");
    }

    private void initRepeatService() {
        final int timeInterval = 1 * 60 * 60 * 1000;
        new Thread(() -> {
            while (!isReStart) {
                send();
                try {
                    Thread.sleep(timeInterval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (isReStart) {
                Thread.interrupted();
                mainActivity.getTextArea_res().setText("原线程已停止\r\n");
                initFirst();
            }
        }).start();
        mainActivity.getTextArea_res().append("设置重复发送完毕\r\n");
    }

    private void send() {
        String url = mainActivity.getTextField_url().getText() + new Date().getTime();
        String type = mainActivity.getComboBox_request_type().getSelectedItem().toString();
        Map<String, Object> params = new LinkedHashMap<>();
        Map<String, String> headers = new LinkedHashMap<>();
        achieveHeaderAndRequest(params, headers);
        if ("GET".equals(type)) {
            String retStr = HttpUtils.doGet(url, params, headers);
            mainActivity.getTextArea_res().setText(retStr);
        } else {
            String retStr = HttpUtils.doPost(url, params, headers);
            resultStrValidate(retStr);
        }
    }

    private void resultStrValidate(String retStr) {
        SimpleDateFormat df_normal = new SimpleDateFormat("MM-dd HH:00:00");
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(retStr);
        } catch (IOException e) {
            e.printStackTrace();
            mainActivity.getTextArea_res().append(df_normal.format(new Date()) + ": 发送失败 " + retStr + "\r\n");
        }
        if (jsonNode != null && jsonNode.has("code") && "100000".equals(jsonNode.get("code").asText())) {
            mainActivity.getTextArea_res().append(df_normal.format(new Date()) + ": 发送成功\r\n");
        } else {
            mainActivity.getTextArea_res().append(df_normal.format(new Date()) + ": 发送失败 " + retStr + "\r\n");
        }
    }

    private void achieveHeaderAndRequest(Map<String, Object> params, Map<String, String> headers) {
        int headerSize = mainActivity.getTableModel_header().getRowCount();
        int requestSize = mainActivity.getTableModel_request().getRowCount();
        for(int i = 0; i < headerSize; i++) {
            if (Boolean.valueOf(mainActivity.getTableModel_header().getValueAt(i, 0)+"").booleanValue()) {
                String key = mainActivity.getTableModel_header().getValueAt(i, 1)+"";
                String value = mainActivity.getTableModel_header().getValueAt(i, 2)+"";
                if (!StrKit.isNull(key) && !StrKit.isNull(value)) {
                    System.out.println(key + "=" + value);
                    headers.put(key, value);
                }
            }
        }

        for(int i = 0; i < requestSize; i++) {
            if (Boolean.valueOf(mainActivity.getTableModel_request().getValueAt(i, 0)+"").booleanValue()) {
                String key = mainActivity.getTableModel_request().getValueAt(i, 1)+"";
                String value = mainActivity.getTableModel_request().getValueAt(i, 2)+"";
                if (!StrKit.isNull(key)) {
                    System.out.println(key + "=" + value);
                    params.put(key, value);
                }
            }
        }

        try {
            params.put("text", compute());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (!params.containsKey("text")) {
            SimpleDateFormat df_normal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            params.put("text", "现在时间：" + df_normal.format(new Date()));
        }
    }

    private void addRow(ComponentEnum componentEnum) {
        Object []rowValues = {new Boolean(true), "",""};
        switch (componentEnum) {
            case BUTTON_ADD_HEADER: mainActivity.getTableModel_header().addRow(rowValues);break;
            case BUTTON_ADD_REQUEST:mainActivity.getTableModel_request().addRow(rowValues);break;
        }
    }

    public static String compute() throws ParseException {
        Date now = new Date();

        SimpleDateFormat df_ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        SimpleDateFormat df_year = new SimpleDateFormat("yyyy");
        SimpleDateFormat df_hour = new SimpleDateFormat("HH");
        String year = df_year.format(now);
        String yearStartStr = year + "-01-01 00:00:00:000";
        String yearEndStr = year + "-12-31 23:59:59:999";
        Date yearStart = df_.parse(yearStartStr);
        Date yearEnd = df_.parse(yearEndStr);
        double pass_time = (now.getTime() - yearStart.getTime()) * 1.0 / (yearEnd.getTime() - yearStart.getTime());
        String t = "#我曾留恋的时光# 咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！咣！大笨钟提醒你：北京时间" + df_hour.format(now) + "点整，2017已悄悄溜走" + pass_time * 100 + "%," + "，时间都去哪儿了？";
        return t;
    }
}
